package leetcode.code0761;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public String makeLargestSpecial(String s) {
		char[] cs = s.toCharArray();
		this.merge(cs, 0, cs.length - 1);
		return new String(cs);
	}

	private void merge(char[] cs, int L, int R) {
		if (L == R) {
			return;
		}
		int one = 0, l = L;
		List<String> list = new ArrayList<>();
		for (int i = L; i <= R; i++) {
			char c = cs[i];
			one += c == '1' ? 1 : -1;
			if (one == 0) {
				if (l == L && i == R) {
					this.merge(cs, L + 1, R - 1);
					return;
				} else {
					this.merge(cs, l, i);
					list.add(new String(cs, l, i - l + 1));
					l = i + 1;
				}
			}
		}
		Collections.sort(list, (a, b) -> b.compareTo(a));
		int p = L;
		for (String s : list) {
			for (char c : s.toCharArray()) {
				cs[p++] = c;
			}
		}
	}

	@Override
	public void debug4() {
		H.compare("111111000111000100110001100100", this.makeLargestSpecial("111001011100110111000111000000"));
		H.compare("1010", this.makeLargestSpecial("1010"));
		H.compare("11100100", this.makeLargestSpecial("11011000"));
		H.compare("1111000011100100", this.makeLargestSpecial("1101100011110000"));

	}


	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
